import {Injectable} from '@angular/core';
import {AppConfig} from '../config';
import {Http, Headers} from '@angular/http';
import {Model} from '../entity/model.model';
import {Tag} from '../entity/tag.model';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class ModelService {
  private readonly param = 'models';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {

  }

  create(model: Model): Promise<Model> {
    return this.http.post(this.url, JSON.stringify(model))
      .toPromise()
      .then(res => {

        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data as Model;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  update(model: Model): Promise<Model> {
    const url = `${this.url}`;
    return this.http.put(url, JSON.stringify(model))
      .toPromise()
      .then(() => model)
      .catch(this.handleError);
  }

  batchDelete(keyIds: number[]): Promise<any> {
    const apiUrl = `${this.url}?items=${keyIds}`;
    // const apiUrl = `http://192.168.15.3:8585/webapi/v1/models?items=${keyIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return result;
            case '-1':
              throw new Error(result.message);
            case '8001':
              return result;
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  /**
   *
   *
   * @memberof ModelService
   */
  getModels(): Promise<Model[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as Model[])
      .catch(this.handleError);
  }

  /**
   * 根据风机型号id获取风机型号
   *
   * @memberof ModelService
   */
  getModelByModelId(modelId: number): Promise<Model> {
    return this.http.get(`${this.url}/${modelId}`)
      .toPromise()
      .then(response => response.code === '200' ? response.data as Model : [])
      .catch(this.handleError);
  }

  /**
   * 根据风机型号得到测点
   *
   * @memberof ModelService
   */
  getTagByModelId(modelId: number): Promise<Tag[]> {
    return this.http.get(`${this.url}/tag/${modelId}`)
      .toPromise()
      .then(response => response.data as Tag[])
      .catch(this.handleError);
  }

  /**
   * 根据风机型号得到显示的测点
   *
   * @param {number} modelId
   * @param {number} categoryId
   * @returns {Promise<Tag[]>}
   * @memberof ModelService
   */
  getShowTagByModelId(modelId: number, categoryId: number): Promise<Tag[]> {
    return this.http.get(`${this.url}/tag2/modelId/${modelId}/categoryId/${categoryId}`)
      .toPromise()
      .then(response => response.code === '200' ? response.data as Tag[] : [])
      .catch(this.handleError);
  }

  /**
   * 获取所有型号
   *
   * @memberof ModelService
   */
  getModelWithFactory(): Promise<Model[]> {
    return this.http.get(`${this.url}/modelFactoryVO`)
      .toPromise()
      .then(response => response.code === '200' ? response.data as Model[] : [])
      .catch(this.handleError);
  }

  // hasModelName(modelName: string, modelId: number) {
  //   let reg=/\//g;
  //   if(reg.test(modelName)){

  //     modelName=modelName.replace(reg,function(string){
  //       return "%2F"
  //     });
  //     console.log(modelName)
  //   }

  //   const url = `${this.url}/modelName/${modelName}/modelId/${modelId}`;

  //   return this.http.get(url).map(response => {
  //     let code = response.code;
  //     switch (code) {
  //       case "3001":
  //         return true;
  //       case "3002":
  //         return false;
  //     }
  //   }).catch(this.handleError);
  // }

  hasModelName(modelName: string, modelId: number) {
    let reg = /\//g;
    if (reg.test(modelName)) {
      modelName = modelName.replace(reg, function (string) {
        return '%2F'
      });
    }
    const url = `${this.url}/getBasicModelByModelName`;
    // const url = `http://192.168.15.3:8585/webapi/v1/models/getBasicModelByModelName`;
    return this.http.post(url, JSON.stringify({modelName, modelId})).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }


  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}


// WEBPACK FOOTER //
// ./src/app/service/model.service.ts
